import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataBaseConnectMain {
    private static Connection conn;

    public static void main(String[] args) {

        System.out.println("The main thread starts executing");

        // 初始化数据库连接
        initConnection();

        System.out.println("Do some data querying and processing");

        // 注册关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                closeConnection();
            }
        });

        System.out.println("The main thread ends execution.");
    }

    private static void initConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=true&", "root", "root");
            System.out.println("Database connection successful！");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void closeConnection() {
        try {
            conn.close();
            System.out.println("Database connection closed！");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}